package ru.xpparty.scanner;

import org.apache.commons.cli.*;
import ru.xpparty.scanner.model.ScanRequest;

public class ArgumentBuilderImpl implements ArgumentsBuilder {
    private static final String PORT_ARG = "p";
    private static final String HOST_ARG = "h";
    private static final String DEFAULT = "default";

    private Parser parser;
    private Options options;


    @Override
    public ScanRequest build(String[] args) {
        parser = new PosixParser();
        options = createOptions();
        try {
            return tryParse(args);
        } catch (ParseException e) {
            throw new IllegalArgumentException(e);
        }
    }

    private ScanRequest tryParse(String[] args) throws ParseException {
        CommandLine line = parser.parse(options, args);
        String ports = line.getOptionValue(PORT_ARG, DEFAULT);
        String ip = line.getOptionValue(HOST_ARG, DEFAULT);

        int startPort;
        int endPort;
        String[] split = ports.split("-");
        if (isOnePort(split)) {
            startPort = endPort = Integer.parseInt(split[0]);
        } else if (isRangeOfPorts(split)) {
            startPort = Integer.parseInt(split[0]);
            endPort = Integer.parseInt(split[1]);
        } else {
            throw new IllegalArgumentException();
        }

        return new ScanRequest(ip, new PortRange(startPort, endPort));
    }

    private Options createOptions() {
        Options options = new Options();
        options.addOption(PORT_ARG, true, "ports");
        options.addOption(HOST_ARG, true, "hosts");
        return options;
    }

    private boolean isRangeOfPorts(String[] split) {
        return split.length == 2;
    }

    private boolean isOnePort(String[] split) {
        return split.length == 1;
    }
}
